import type { FormProps } from 'antd';
import { Button, Form, message, Input } from 'antd';
import { useNavigate } from 'react-router-dom'
import useJwt from '../../UseJwt';
import loginSvg from '../../assets/login.svg'

type FieldType = {
  username: string;
  password: string;
};
function Login() {
  const navigate = useNavigate()
  const login = async (username: string, password: string) => {
    const res = await useJwt.login({
      username,
      password
    }) as any

    
    if (res.code !== 200) {
      message.warning('登录失败！')
      return
    }

    message.success('登录成功！')

    // 保存token
    localStorage.setItem('token', res.data)
    
    // 获取用户信息
    useJwt.userInfo()

    // 跳转路由到首页
    navigate('/home')
  }
  
  const onFinish: FormProps<FieldType>['onFinish'] = (userInfo) => {
    console.log('Success:', userInfo);
    login(userInfo.username, userInfo.password)
  };
  
  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div className="flex justify items-center h-screen bg-[#f8f7fa]">
      <div  className='flex-1'>
        <img src={loginSvg} className='m-auto'/>
      </div>
      <div className="h-screen w-[400px] shadow-md rounded-md p-6 pt-80 bg-white">
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 24 }}
          style={{ maxWidth: 600 }}
          initialValues={{ username: 'admin', password: '123456' }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          layout="vertical"

        >
          <Form.Item<FieldType>
            label="用户名"
            name="username"
          >
            <Input
              placeholder='请输入用户名'
            />
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="password"
          >
            <Input.Password
              placeholder='请输入用户名'
            />
          </Form.Item>
          
          <Form.Item wrapperCol={{ span: 24 }}>
            <Button type="primary" htmlType="submit" className='w-full'>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
